package com.snowflake.ecatalog.web.admin;

import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.utils.Collections3;
import org.springside.modules.web.Servlets;

import com.snowflake.ecatalog.entity.Profile;
import com.snowflake.ecatalog.service.admin.CompanyService;
import com.snowflake.ecatalog.service.admin.ProfileService;

/**
 * Profile管理的Controller, 使用Restful风格的Urls:
 * 
 * List page : GET /profile/ Create page : GET /profile/create Create action :
 * POST /profile/create Update page : GET /profile/update/{id} Update action :
 * POST /profile/update Delete action : GET /profile/delete/{id}
 * 
 */
@Controller
@RequestMapping(value = "/profile")
public class ProfileController {

	private static final int PAGE_SIZE = 10;

	@Autowired
	private ProfileService profileService;
	@Autowired
	private CompanyService companyService;

	@RequestMapping(value = "")
//	@RequestParam(value = "standard", defaultValue = "-1") long standardId,
	public String list(	@RequestParam(value = "page", defaultValue = "1") int pageNumber, Model model, ServletRequest request) {
		Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
		Page<Profile> profiles = profileService.getProfiles(searchParams, pageNumber, PAGE_SIZE);
		model.addAttribute("profiles", profiles);
		model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
		return "admin/profileList";
	}

	@RequestMapping(value = "create", method = RequestMethod.GET)
	public String createForm(Model model) {
		Profile newProfile = new Profile();
		model.addAttribute("profile", newProfile);
		model.addAttribute("action", "create");
		return "admin/profileForm";
	}

	@RequestMapping(value = "create", method = RequestMethod.POST)
	public String create(@Valid Profile newProfile, RedirectAttributes redirectAttributes, ServletRequest request) {
		profileService.saveProfile(newProfile);
		redirectAttributes.addFlashAttribute("message", "创建彩页成功");
		return "redirect:/profile/";
	}

	@RequestMapping(value = "update/{id}", method = RequestMethod.GET)
	public String updateForm(@PathVariable("id") Long id, Model model) {
		model.addAttribute("profile", profileService.getProfile(id));
		model.addAttribute("action", "update");
		return "admin/profileForm";
	}

	@RequestMapping(value = "update", method = RequestMethod.POST)
	public String update(@Valid @ModelAttribute("preloadProfile") Profile profile,
			RedirectAttributes redirectAttributes, ServletRequest request) {
		profileService.updateProfile(profile);
		redirectAttributes.addFlashAttribute("message", "更新彩页成功");
		return "redirect:/profile/";
	}

	@RequestMapping(value = "getEnabledProfile", method = RequestMethod.POST)
	public @ResponseBody
	Map<?, ?> getEnabledProfile(@RequestParam(value = "exludeIdList[]", required = false) List<Long> exludeIdList) {
		Map<?, ?> profileMap = null;
		// 以彩页Id为key，彩页名称为value
		List<Profile> profileList = profileService.getEnabledProfile(exludeIdList);
		if (CollectionUtils.isNotEmpty(profileList)) {
			profileMap = Collections3.extractToMap(profileList, "id", "name");
		}

		return profileMap;
	}

	/**
	 * 使用@ModelAttribute, 实现Struts2
	 * Preparable二次部分绑定的效果,先根据form的id从数据库查出Profile对象 ,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此本方法在该方法中执行.
	 */
	@ModelAttribute("preloadProfile")
	public Profile getProfile(@RequestParam(value = "id", required = false) Long id) {
		if (id != null) {
			Profile profile = profileService.getProfile(id);
			profile.setCompanys(null);
			return profile;
		}
		return null;
	}
	
	@RequestMapping(value = "enable/{id}")
	public String enable(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
		profileService.enableProfile(id);
		redirectAttributes.addFlashAttribute("message", "启用彩页成功");
		return "redirect:/profile/";
	}

	@RequestMapping(value = "disable/{id}")
	public String disable(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
		profileService.disableProfile(id);
		redirectAttributes.addFlashAttribute("message", "禁用彩页成功");
		return "redirect:/profile/";
	}

	@RequestMapping(value = "delete/{id}")
	public String delete(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
		// 校验分类标准下是否关联分类
		if (existUserOrCompanyInProfile(id)) {
			redirectAttributes.addFlashAttribute("message", "该彩页下已关联用户或客户档案，不能删除");
		} else {
			profileService.deleteProfile(id);
			redirectAttributes.addFlashAttribute("message", "删除彩页成功");
		}
		return "redirect:/profile/";
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "select/{id}")
	public String select(@PathVariable("id") Long id, RedirectAttributes redirectAttributes, HttpSession session) {
		session.setAttribute("PROFILE_ID", id);
		Map<Long, String> profiles = (Map<Long, String>) session.getAttribute("PROFILE_SELECT");
		redirectAttributes.addFlashAttribute("message", "当前彩页成功切换为 "+profiles.get(id));
		return "redirect:/startup/";
	}
	
	private boolean existUserOrCompanyInProfile(Long profileId) {
		return profileService.existUserOrCompanyInProfile(profileId);
	}

}
